

package com.maoshi.shop.mp.comment.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.maoshi.shop.common.util.PageParam;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.mp.comment.model.WeiXinMenu;
import com.maoshi.shop.mp.comment.service.WeixinMenuService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 *
 * @author lgh on 2019/05/13.
 */
@RestController
@RequestMapping("/weixin/weixinMenu")
public class WeixinMenuController {

    @Autowired
    private WeixinMenuService weixinMenuService;

	/**
	 * 分页获取
	 */
    @GetMapping("/page")
	//@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:page')")
	public ResponseEntity<IPage<WeiXinMenu>> page(WeiXinMenu weiXinMenu,PageParam<WeiXinMenu> page){
		IPage<WeiXinMenu> list = weixinMenuService.page(page);
		return ResponseEntity.ok(list);
	}





    /**
	 * 获取信息
	 */
	@GetMapping("/info")
	//@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:info')")
	public ResponseEntity<String> info(){
		WeiXinMenu weiXinMenu = weixinMenuService.getById(1);
		//如果为空则创建一个
		if(weiXinMenu == null){
			weiXinMenu =new WeiXinMenu();
			weiXinMenu.setId(1);
			weiXinMenu.setMenu("{ \"button\": [] }");
			weiXinMenu.setUpdateTime(new Date());
			weixinMenuService.save(weiXinMenu);
		}
		return ResponseEntity.ok(weiXinMenu.getMenu());
	}

	/**
	 * 保存
	 */
	@PostMapping
//	@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:save')")
	public ResponseEntity<Void> save(@RequestBody @Valid WeiXinMenu weiXinMenu){
		weixinMenuService.save(weiXinMenu);
		return ResponseEntity.ok().build();
	}

	/**
	 * 修改
	 */
	@PutMapping
	//@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:update')")
	public ResponseEntity<Void> update(@RequestBody @Valid WeiXinMenu weiXinMenu){
		System.err.println(weiXinMenu.getMenu());
		weiXinMenu.setId(1);
		weiXinMenu.setUpdateTime(new Date());
		weiXinMenu.setMenu(weiXinMenu.getMenu());
		weixinMenuService.updateById(weiXinMenu);
		return ResponseEntity.ok().build();
	}


	/**
	 * 发布
	 */
	@PutMapping("release")
	//@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:update')")
	public ResponseEntity<Void> release(){
		try {
			weixinMenuService.release();
		} catch (WxErrorException e) {
			e.printStackTrace();
			throw  new MaoshiShopBindException("错误: Code=" + e.getError().getErrorCode() + ", Msg=" + e.getError().getErrorMsg() );
		}
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/{id}")
	//@PreAuthorize("@pms.hasPermission('weixin:weiXinMenu:delete')")
	public ResponseEntity<Void> delete(@PathVariable Long id){
		weixinMenuService.removeById(id);
		return ResponseEntity.ok().build();
	}
}
